<template>
  <div class="app-container">
    <el-card v-loading="loading" class="tree-card">
      <TreeTools :item="header" :isbool="true" @show-close="dialogVisible = true" />
      <el-tree :data="dataList" :props="defaultProps">
        <template #default="{data}">
          <TreeTools :item="data" @show-close="showDialog" />
        </template>
      </el-tree>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closedialog"
      @open="dialogOpen"
    >
      <el-form ref="departRef" :model="departForm" :rules="departRules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departForm.name" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="departForm.code" style="width:80%" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="departForm.manager" style="width:80%" placeholder="请选择">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="departForm.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import transTree from '@/utils/transTree'
import { getDepartment, addDepartment, getDepartDetail, updateDepartment } from '@/api/department'
import TreeTools from '@/layout/components/tree-tools.vue'
import { getManagerList } from '@/api/employee.js'
export default {
  components: { TreeTools },
  data() {
    const validateCode = (rules, value, cb) => {
      if (this.departForm.id && value === this.nodeData.code) {
        cb()
        return
      }
      const isSame = this.originList.some(item => item.code === value)
      isSame ? cb(new Error('部门编码不能重复')) : cb()
    }
    const validateName = (rules, value, cb) => {
      // 1. 找到所有的同级部门
      let broArr = []
      if (this.departForm.id) {
      // 编辑
      // 编辑时，且 name 和原来的 name 一样的，直接校验通过
        if (value === this.nodeData.name) {
          cb()
          return
        }
        // 以 this.nodeData.pid 作为父亲，找他所有的孩子
        broArr = this.originList.filter(item => item.pid === this.nodeData.pid)
      } else {
      // 添加
      // 以 this.nodeData.id 作为父亲，找他所有的孩子
        broArr = this.originList.filter(item => item.pid === this.nodeData.id)
      }

      // 2. 只要当前添加的部门名称和任意一个同级部门的名称相等，就不通过校验
      const isSame = broArr.some(item => item.name === value)
      if (isSame) {
        // 校验不通过
        cb(new Error('同级部门名称不能重复！'))
      } else {
        // 校验通过
        cb()
      }
      // const broArr = this.originList.filter(item => item.pid === this.nodeData.id)
      // const isSame = broArr.some(item => item.name === value)
      // if (isSame) {
      //   cb(new Error('同级部门名称不能重复！'))
      // } else {
      //   cb()
      // }
    }
    return {
      loading: false,
      managerList: [],
      originList: [],
      nodeData: {},
      departForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      departRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateName, trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      header: {
        name: '船只教育',
        manager: '负责人',
        id: ''
      },
      dataList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false
    }
  },
  computed: {
    title() {
      return this.departForm.id ? '编辑' : '新增'
    }
  },
  created() {
    this.getDepartmentLIst()
  },
  methods: {
    async getDepartmentLIst() {
      this.loading = true
      try {
        const res = await getDepartment()
        this.dataList = transTree(res.data.depts)
        this.originList = res.data.depts
        console.log(this.nodeData)
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    closedialog() {
      this.dialogVisible = false
      this.$refs.departRef.resetFields()
    },
    showDialog(item, type) {
      this.dialogVisible = true
      this.nodeData = item
      if (type === 'edit') {
        this.getDetail()
      }
    },
    async dialogOpen() {
      const { data } = await getManagerList()
      console.log(data)
      this.managerList = data
    },
    submit() {
      // 添加子部门/编辑部门
      this.$refs.departRef.validate(async valid => {
        if (!valid) return
        if (this.departForm.id) {
          await updateDepartment(this.departForm)
        } else {
          await addDepartment({ ...this.departForm, pid: this.nodeData.id })
        }
        this.$message.success(this.title + '成功')
        this.dialogVisible = false
        this.dialogClose()
        this.getDepartmentLIst()
      })
    },
    async getDetail() {
      const res = await getDepartDetail(this.nodeData.id)
      this.departForm = res.data
    },
    dialogClose() {
      this.dialogVisible = false
      // 重置表单
      this.$refs.departRef.resetFields()
      // 重置数据
      this.departForm = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      }
    }

  }
}
</script>
<style lang='scss' scoped>
.app-container {
  padding: 20px;
}
.tree-card {
  padding: 30px;
}
</style>
